import {
    addUserDao,
    updateUserDao
} from "../Dao/userDao.js"
import {
    findUserDao
} from "../Dao/loginDao.js"
import {
    getRandomStr
} from "../tools/index.js"
import md5 from "md5"
import fs from 'fs/promises'
import jwt from "jsonwebtoken"

export const registerServ = async ({
    username,
    nickname
}) => {
    if (!nickname) {
        nickname = "新用户" + getRandomStr(6)
    }
    const dirs = await fs.readdir("./static/avatar")
    const avatar = dirs[Math.floor(Math.random() * dirs.length)]
    return await addUserDao({
        username,
        nickname,
        avatar: "http://localhost:8090/" + avatar,
        password: md5("123123")
    })
}



export const loginServ = async (userInfo) => {
    const user = await findUserDao(userInfo.username)
    console.log('user', user);

    if (!user) {
        return {
            code: 1,
            msg: "用户名不存在"
        }
    }

    if (md5(userInfo.password) === user.password) {
        //登陆成功
        console.log('userInfo', userInfo.noLogin);
        if (userInfo.noLogin) {
            const token = jwt.sign({
                data: user.username
            }, "buka", {
                expiresIn: "30d"
            })
            return {
                code: 0,
                msg: "登录成功",
                token,
                data: user
            }
        } else {
            //未勾选免密登录
            const token = jwt.sign({
                data: user.username
            }, "buka", {
                expiresIn: "1d"
            })
            return {
                code: 0,
                msg: "登录成功",
                data: user,
                token
            }
        }
    } else {
        return {
            code: 1,
            msg: "密码错误"
        }
    }
}



export const checkAuthServ = async (username, password) => {
    const user = await findUserDao(username);
    if (user) {
        if (user.password === md5(password)) {
            return {
                code: 0,
                msg: "ok"
            }
        } else {
            return {
                code: 1,
                msg: "密码错误"
            }
        }
    } else {
        return {
            code: 1,
            msg: "用户名不存在"
        }
    }
}


export const updatePwdServ = async (username, password) => {
  return await updateUserDao(username,{password:md5(password)});
}

export const updateUserServ = async (username,updateObj)=>{
    const res = await updateUserDao(username,updateObj)
    return {
        code:0,
        msg:"ok",
        data:res
    }
} 